//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include <_bootmods.h>

#define MAX_PATH 256

char *GetFullPathByEnv(char *fullpath, char *env, char *addpath, char *name)
{
    char *pszEnvPath;
    pszEnvPath = getenv(env);
    if(NULL == pszEnvPath){
        return NULL;
    }
    strcpy(fullpath, pszEnvPath);
    strcat(fullpath, "/");
    if(NULL != fullpath){
        strcat(fullpath, addpath);
        strcat(fullpath, "/");
    }
    if(NULL != name){
        strcat(fullpath, name);
    }

    return fullpath;
}

char *GetModuleFullPath(char *pszFullPath, char *pszMName)
{
    char pszPath[MAX_PATH];

    assert(pszFullPath && pszMName);

    //First get the moudle file in current directory
    if (realpath(pszMName, pszFullPath) != NULL){
        printf("get bootmod:%s.\n", pszFullPath);
        return pszFullPath;
    }

    //Try get the fullpath through "XDK_SIMULATOR_RESOURCE"
    if(NULL != GetFullPathByEnv(pszPath, "XDK_SIMULATOR_RESOURCE", NULL, pszMName)){
        if (NULL != realpath(pszPath, pszFullPath)){
            printf("get bootmod:%s.\n", pszFullPath);
            return pszFullPath;
        }
    }

    //Try get the fullpath through "XDK_COMMON_RESOURCES" and "i18n"
    if(NULL != GetFullPathByEnv(pszPath, "XDK_COMMON_RESOURCES", "i18n", pszMName)){
        if (NULL != realpath(pszPath, pszFullPath)){
            printf("get bootmod:%s.\n", pszFullPath);
            return pszFullPath;
        }
    }

    return NULL;
}

extern "C" int GetBootModlesInfo(BootModule *pBootModules, int iNumberOfBootModules)
{
    char szFileName[MAX_PATH];
    FILE *fp = NULL;
    for (int i = 0; i < iNumberOfBootModules; i++) {
        if(NULL == GetModuleFullPath(szFileName, pBootModules[i].szName)){
            printf("Can not get BootModule file.\n");
            return 1;
        }

        fp = fopen(szFileName, "rb");
        if (NULL == fp) {
            printf("Can not open BootModule file.\n");
            return 1;
        }
        assert(fp);
        fseek(fp, 0, SEEK_END);
        pBootModules[i].size = ftell(fp);
        pBootModules[i].pFile = malloc(pBootModules[i].size);
        assert(pBootModules[i].pFile);
        fseek(fp, 0, SEEK_SET);
        fread(pBootModules[i].pFile, 1, pBootModules[i].size, fp);
        fclose(fp);
    }

    return 0;
}

extern "C" void DisposeModlesInfo(BootModule *pBootModules, int iNumberOfBootModules)
{
    for (int i = 0; i < iNumberOfBootModules; i++) {
        if (pBootModules[i].pFile) {
            free(pBootModules[i].pFile);
        }
    }
}
